package com.ld.security.common.core.anno.aop;

import com.ld.security.common.core.anno.EventKey;
import com.ld.security.common.core.util.EventUtil;
import com.ld.security.common.core.util.SpringUtil;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.concurrent.CompletableFuture;

@Component
@Aspect
@Order(5)
public class EventAop {



    @Pointcut("@annotation(com.ld.security.common.core.anno.EventKey)")
    public void aop() {

    }

    @Around("aop()")
    public Object doAroundAdvice(ProceedingJoinPoint pjp) throws Throwable{

       MethodSignature ms = (MethodSignature) pjp.getSignature();
       Method method = ms.getMethod();
       EventKey eventKey =  AnnotationUtils.findAnnotation(method, EventKey.class);
       Object val=null;
       if(eventKey.before()){
            val =  pjp.proceed();
       }



       Object[] args =  pjp.getArgs();

       if(eventKey.async()){
           EventUtil.asyncDispatch(eventKey.value(),eventKey.methodName(),args);

       }else{
           EventUtil.dispatch(eventKey.value(),eventKey.methodName(),args);
       }

       if(!eventKey.before()){
           val =  pjp.proceed();
       }

       return val;
    }


}
